/*
 * @Description: 自增字段 上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-11-01 09:32:07
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { AutoFilingReducer } from '../reducers/AutoFilingReducer';
import {
  ADD_SELECT_FIELD_LIST,
  DELETE_SELECT_FIELD_LIST,
  SET_SELECT_AT,
  SET_SELECT_FIELD_LIST,
  SET_SELECT_FOND,
  SET_SELECT_FOND_ID,
  SET_SELECT_AT_ID
} from '../constants';
import {
  addFiling,
  deleteFiling,
  fetchFilingList,
  editFiling
} from '@/api/rulesettings/ruleSetting';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectFondId: 0,
  selectATId: 0,

  commonRule: {
    pageNum: '',
    serialLength: '',
    defaultSpec: ''
  },
  list: [],
  loading: false,

  // 选中的表格条目
  selectItems: []
};

const AutoFilingContext = createContext();

const AutoFilingContextProvider = (props) => {
  const [state, dispatch] = useReducer(AutoFilingReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的全宗
     */
    setSelectFondId(id) {
      dispatch({ type: SET_SELECT_FOND_ID, id });
    },

    /**
     * @description: 设置选中的档案类型ID
     */
    setSelectATId(id) {
      dispatch({ type: SET_SELECT_AT_ID, id });
    },

    /**
     * @description: 获取分组字段列表
     */
    getSelectFields() {
      const query = {
        atCode: state.selectAT.atCode,
        atType: state.selectAT.atType
      };
      fetchFilingList(query).then((res) => {
        const { data } = res;
        console.log(data);
        dispatch({ type: SET_SELECT_FIELD_LIST, data });
      });
    },

    /**
     * @description: 增加分组字段
     * @param {*}
     */
    addAutoFilling(query) {
      query.atCode = state.selectAT.atCode;
      query.atType = state.selectAT.atType;
      addFiling(query).then((res) => {
        const { data } = res;
        data.key = data.fieldId;
        console.log('add: ', data);
        dispatch({ type: ADD_SELECT_FIELD_LIST, data });
      });
    },

    /**
     * @description: 删除分组字段
     * @param {*}
     */
    deleteGroupField(id) {
      const ids = id instanceof Array ? id.join(',') : id;
      deleteFiling(ids).then((res) => {
        const data = res.data.map((id) => parseInt(id, 10));
        console.log('delete', data);
        dispatch({ type: DELETE_SELECT_FIELD_LIST, ids: data });
      });
    },

    saveFilingFunc(query) {
      // query.archiveTypeId = state.selectLevel.activeLevelId;
      query.atCode = state.selectAT.atCode;
      query.atType = state.selectAT.atType;
      return new Promise((resolve, reject) => {
        editFiling(query).then(() => {
          message.success('保存成功');
        });
      });
    }
  };

  // watch选中的单位来加载立卷规则
  useEffect(() => {
    if (JSON.stringify(state.selectAT) !== '{}') {
      actions.getSelectFields();
    }
  }, [state.selectAT]);

  return (
    <AutoFilingContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </AutoFilingContext.Provider>
  );
};

export const useAutoFilingContext = () => {
  return useContext(AutoFilingContext);
};

export { AutoFilingContext, AutoFilingContextProvider };
